package com.guazi.trackingtest;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by lqy on 2018/3/13.
 */

public class Sender {
    static final int PORT = 4444;

    private Server mServer;
    private BlockingQueue<PackData> mBlockingQueue = new LinkedBlockingQueue<>();

    public Sender() {

    }

    public void start(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                mServer = new Server(PORT);
                mServer.start();
            }
        }).start();
    }

    public void sendDataToJs() throws InterruptedException, IOException {
        PackData packData = mBlockingQueue.take();
        mServer.broadcast(packData2json(packData));
    }

    private String packData2json(PackData packData) {
        return JSON.toJSONString(packData);
    }

    public void addPackData(PackData packData) {
        mBlockingQueue.add(packData);
    }

    public void stop() {
        try {
            mServer.stop();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
